package com.shuai.api_platform.service.impl;

import com.shuai.api_platform.model.request.SendEmailRequest;
import com.shuai.api_platform.service.EmailService;
import com.shuai.api_platform.utils.EmailCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Service
@Slf4j
public class EmailServiceImpl implements EmailService {

    /**
     * 验证码发送服务
     */
    @Autowired
    private JavaMailSender javaMailSender;


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${spring.mail.username}")
    private String fromUser;


    /**
     * 发送验证码
     */
    @Override
    public String sendCodeToUser(SendEmailRequest request) throws MessagingException {
        String toUser = request.getEmail();
        String title = request.getTitle();
        String prompt = request.getPrompt();
        String warning = request.getWarning();
        // 调用验证码服务发送验证码
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        mimeMessage.setFrom(fromUser);
        String code = EmailCodeUtils.generateCode();
        String text = prompt + code + warning;
        mimeMessage.setSubject(title);
        mimeMessage.setText(text);
        mimeMessage.setRecipients(Message.RecipientType.TO, toUser);
        javaMailSender.send(mimeMessage);
        return code;
    }

}
